package hhtc.jsjds.service;

import hhtc.jsjds.config.UploadProperties;
import hhtc.jsjds.enums.StatusCodeEnum;
import hhtc.jsjds.exception.XscoderException;
import hhtc.jsjds.utils.OssUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Map;

/**
 * @Author: cuzz
 * @Date: 2018/11/2 14:09
 * @Description:
 */
@Service
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {

    @Autowired
    @Qualifier("UploadProperties")
    private UploadProperties prop;


    public String upload(MultipartFile file) {
        try {
            // 1、图片信息校验
            // 1)校验文件类型
            String type = file.getContentType();

            if (!prop.getAllowTypes().contains(type)) {
                throw new XscoderException(StatusCodeEnum.INVALID_FILE_TYPE);
            }
            // 2)校验图片内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                throw new XscoderException(StatusCodeEnum.INVALID_FILE_TYPE);
            }
            Map<String, Object> uploadResult = OssUtils.upload(file, "jsjsjds-resources", "jsjsjds/");
            //1. 生成一个随机6为数字, 作为验证码
            return String.valueOf(uploadResult.get("url"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
